package cn.smile.task;

import cn.smile.business.core.*;
import cn.smile.business.log.IBanAddressService;
import cn.smile.business.log.ILogInfoService;
import cn.smile.business.wechat.IWeChatApiService;
import cn.smile.utils.DateFormatUtil;
import cn.smile.utils.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;

import java.util.Date;

/**
 * 定时任务调用类
 *
 * @author smile-jt
 */
@Slf4j
@Component
@EnableScheduling
public class MyScheduleTask {
    @Resource
    private IBanAddressService ipService;
    @Resource
    private ISysNotPermissionService permissionService;
    @Resource
    private IFileUploadService fileService;
    @Resource
    private ISysUserService userService;
    @Resource
    private ILogInfoService logService;
    @Resource
    private IReqWithoutService withoutService;
    @Resource
    private IWeChatApiService weChatApiService;

    /**
     * 每10秒执行一次
     */
    @Async
    @Scheduled(cron = "0/10 * * * * ?")
    public void tenSecondsTask() {
        this.writeBanIp();
        this.writeNotPer();
    }

    /**
     * 每分钟执行一次
     */
    @Async
    @Scheduled(cron = "0 0/1 * * * ?")
    public void tenMinuteTask() {
        this.pollingWeChatPublish();
    }

    /**
     * 每小时执行一次
     */
    @Async
    @Scheduled(cron = "0 0 * * * ?")
    public void hourTask() {
    }

    /**
     * 每天执行一次
     */
    @Async
    @Scheduled(cron = "0 0 0 * * ?")
    public void everyDayTask() {
        this.deleteFile();
        this.resetTouristInfo();
        this.deleteLogs();
    }

    /**
     * 每月执行一次
     */
    @Async
    @Scheduled(cron = "0 0 0 1 * ?")
    public void everyMonthTask() {
    }

    /**
     * 写入禁止访问IP到Redis
     */
    private void writeBanIp() {
        ThreadPoolUtil.newTask(() -> ipService.writeIpToRedis());
    }

    /**
     * 写入忽略鉴权URI到Redis
     */
    private void writeNotPer() {
        ThreadPoolUtil.newTask(() -> permissionService.writeToRedis());
    }

    /**
     * 删除过期文件
     */
    private void deleteFile() {
        ThreadPoolUtil.newTask(() -> fileService.autoDelFile());
    }

    /**
     * 重置游客账号信息
     */
    private void resetTouristInfo() {
        ThreadPoolUtil.newTask(() -> userService.resetTourist());
    }

    /**
     * 删除日志
     */
    private void deleteLogs() {
        //日志文件仅保留30天
        ThreadPoolUtil.newTask(() -> logService.taskDelInfo(DateFormatUtil.addDays(new Date(), -30)));
        ThreadPoolUtil.newTask(() -> withoutService.taskDelInfo(DateFormatUtil.addDays(new Date(), -30)));
    }

    /**
     * 轮询微信公众号文章发布结果
     */
    private void pollingWeChatPublish() {
        ThreadPoolUtil.newTask(() -> weChatApiService.pollingPublish());
    }
}
